package cn.com.utt.unms.service.impl;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import cn.com.utt.common.message.StaInfo;
import cn.com.utt.common.protorpc.RPCClient;
import cn.com.utt.common.util.MqttDeviceClientConfig;
import cn.com.utt.common.util.Token;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.unms.mapper.UserCountMapper;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.service.ClientService;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.UserCountService;
import cn.com.utt.unms.vo.GraphQueryResponse;

@Service("userCountService")
public class UserCountServiceImpl implements UserCountService {

	@Autowired
	private UserCountMapper userCountMapper;
	
	@Autowired
	private DeviceService deviceService;
	
	@Autowired
	private ClientService clientService;
	
	@Autowired
	private RPCClient rpcClient;
	
	@Override
	public RestResult getPieByType(Long networkId,Byte type) {
		RestResult result = new RestResult();
		List<Device> devices = deviceService.queryDevicesByNetworkIds(new ArrayList<Long>(){{add(networkId);}});
		List<String> sns = new ArrayList<>();
		for (Device device : devices) {
			sns.add(device.getSn());
		}
		List<Map<String,Object>> count = null;  
		if(sns.size() > 0){
			//userRecordService.updateUserRecordStatus(sns);
			switch (type)
			{
			case 1: //按ssid统计
				count = userCountMapper.getPieBySsid(sns);
				break;
			case 2: //按接入方式统计
				count = userCountMapper.getPieByAccessType(sns);
				break;
			case 3: //按操作系统统计
				break;
			default:
				break;
			}
		}
		Map<String,Integer> temp = new HashMap<>();
		if(count != null){
			for (Map<String,Object> c : count) {
				temp.put(c.get("type").toString(), Integer.parseInt(c.get("total").toString()));
			}
		}
		ArrayList<Map.Entry<String, Integer>> data = sortMap(temp);
		if(type == 2){
			for (int i = 0; i < data.size(); i++) {
				Integer value = data.get(i).getValue();
				switch (data.get(i).getKey()) {
				case "1":
					data.set(i, new AbstractMap.SimpleEntry("2.4G", value));
					break;
				case "2":
					data.set(i, new AbstractMap.SimpleEntry("5G", value));
					break;
				default:
					break;
				}
			}
		}
		if(data.size() > 3){
			Integer four = 0;
			for (int i = 3; i < data.size(); i++) {
				four += data.get(i).getValue();
			}
			data.set(3, new AbstractMap.SimpleEntry("其他", four));
			result.put("data", data.subList(0, 4));
			return result;
		}
		System.out.println(JSON.toJSONString(data));
		result.put("data", data);
		return result;
	}
	
	public ArrayList<Map.Entry<String, Integer>> sortMap(Map map) {
		List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) {
				return obj2.getValue() - obj1.getValue();
			}
		});
		return (ArrayList<Entry<String, Integer>>) entries;
	}

	@Override
	public RestResult getLine(Long networkId,Integer range) {
		Date d = new Date();
		Long endTime = d.getTime();
		Long startTime;
		Calendar calendar = Calendar.getInstance();
		switch (range)
		{
		case 3: //一月
			calendar.setTime(d);    
			calendar.add(Calendar.MONTH, -1);
			Date m = calendar.getTime();
			startTime = m.getTime();
			break;
		case 2: //一周
			calendar.setTime(d);    
			calendar.add(Calendar.WEEK_OF_YEAR, -1);
			Date w = calendar.getTime();
			startTime = w.getTime();
			endTime=d.getTime()-60*1000*10;
			break;
		case 1: //一天
			calendar.setTime(d);    
			calendar.add(Calendar.DAY_OF_WEEK, -1);
			Date day = calendar.getTime();
			startTime = day.getTime();
			endTime=d.getTime()-60*1000;
			break;
		default: //一天
			calendar.setTime(d);    
			calendar.add(Calendar.DAY_OF_WEEK, -1);
			startTime = calendar.getTime().getTime();
			endTime=d.getTime()-60*1000;
			break;
		}
		RestResult result = new RestResult();
		List<GraphQueryResponse> resps = clientService.queryHistoryByNetwork(networkId, startTime/1000, endTime/1000);
		result.put("data", resps);
		return result;
	}
	
	@Override
	public void refresh(long groupId) {
		List<Device> devices = deviceService.queryChildrenDevicesByGroupId(groupId);
		for (Device device : devices) {
			String topic = MqttDeviceClientConfig.router(device.getSn());
			StaInfo staInfo = new StaInfo();
			staInfo.setId(Token.getToken());
			try {
				 rpcClient.send(topic, staInfo);
			} catch (Exception e) {
				System.out.println("exception");
			}
		}
	}

}
